using Engine;
using Game;
using GameEntitySystem;
using TemplatesDatabase;

namespace SCIENEW {
    public class ComponentAirBlower : Component, IUpdateable {

        public SubsystemEnginePower m_subsystemEnginePower;
        public ComponentBlockEntity m_componentBlockEntity;
        public SubsystemTerrain m_subsystemTerrain;

        public UpdateOrder UpdateOrder => UpdateOrder.Default;

        public override void Load(ValuesDictionary valuesDictionary, IdToEntityMap idToEntityMap) {
            base.Load(valuesDictionary, idToEntityMap);
            m_subsystemEnginePower = Project.FindSubsystem<SubsystemEnginePower>(true);
            m_componentBlockEntity = Entity.FindComponent<ComponentBlockEntity>(true);
            m_subsystemTerrain = Project.FindSubsystem<SubsystemTerrain>(true);
        }

        public bool IsWorking() => m_subsystemEnginePower.IsPowered(m_componentBlockEntity.Coordinates, out _);

        public void Update(float dt) {
            ReplaceFurnace(m_componentBlockEntity.Coordinates);
        }

        public virtual void ReplaceFurnace(Point3 coordinates) {
            TerrainChunk chunkAtCell = m_subsystemTerrain.Terrain.GetChunkAtCell(coordinates.X, coordinates.Z);
            if (chunkAtCell != null
                && chunkAtCell.State == TerrainChunkState.Valid) {
                int cellValue = m_subsystemTerrain.Terrain.GetCellValue(coordinates.X, coordinates.Y, coordinates.Z);
                int direction = IlluminableDevice.GetDirection_Static(cellValue);
                int deviceValue = DevicesBlockManager.GetDeviceValueByType(typeof(AirBlowerDevice), IsWorking() ? 0b100 | direction : direction);
                m_subsystemTerrain.ChangeCell(coordinates.X, coordinates.Y, coordinates.Z, deviceValue);
            }
        }
    }
}